package org.nulldevice.tankshot.images;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

public class AnimationRepresentant extends ImageRepresentant {

	protected ArrayList<BufferedImage> animationImages = null;
	protected long duration;
	protected boolean repeatAnimation = false;

	// duration is the duration of one whole animation cycle
	public AnimationRepresentant(BufferedImage image, long duration,
			boolean repeatAnimation) {
		super(image, 0, 0);
		this.duration = duration;
		animationImages = new ArrayList<BufferedImage>();
		Iterator<ImageReader> readers = ImageIO.getImageReadersBySuffix("gif");
		if (readers.hasNext()) {
			ImageReader reader = readers.next();
			try {
				reader
						.setInput(ImageIO
								.createImageInputStream(getClass()
										.getResource(
												"/org/nulldevice/tankshot/images/explosion.gif")
										.openStream()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// reader.setInput( ImageIO.createImageInputStream(((URL)
			// ImageIO.createImageInputStream(getClass().getResource("explosion.gif").openStream())).openStream()));

			int n;
			try {
				n = reader.getNumImages(true);
				for (int i = 0; i < n; i++) {
					BufferedImage tempimage = reader.read(i);
					animationImages.add(tempimage);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else
			System.err.println("no image reader");
	}

	// delta is the time (in milliseconds between the first call
	public void draw(Graphics g, int x, int y, double angle, long delta) {
		if (delta > duration) {
			if (repeatAnimation) {
				// we start the animation loop again
				delta = delta % duration;
			} else {
				// the animation is over, so we do not draw it again
				return;
			}
		}
		int numberOfImageToDraw = (int) ((delta) / (duration / animationImages
				.size()));

		if (numberOfImageToDraw < 0)
			numberOfImageToDraw = 0;
		if (numberOfImageToDraw > animationImages.size() - 1)
			numberOfImageToDraw = animationImages.size() - 1;

		g.drawImage(animationImages.get(numberOfImageToDraw), x + offsetX
				- animationImages.get(0).getWidth() / 2, y + offsetY
				- animationImages.get(0).getHeight() / 2, null);

		// if (explosionAnimationIt.hasNext()) {
		// BufferedImage i = explosionAnimationIt.next();
		// g.drawImage(i, x + offsetX - i.getWidth() / 2, y + offsetY
		// - i.getHeight() / 2, null);
		// }
		// else
		// this.destroyed = true;
	}

}
